/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.ycl.ybk.e2p.yb.main;

import cn.ac.iie.di.ban.ycl.ybk.e2p.yb.service.FJRThreadTask;
import cn.ac.iie.di.ban.ycl.ybk.e2p.yb.tools.PatternTools;
import iie.mm.client.ClientAPI;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

/**
 *
 * @author wmr
 */
public class BanBkE2p {

//    private static Logger logger = Logger.getLogger(BanBkE2p.class);
    private static Logger logger = null;
    public static String localFilePathBase = null;
    public static String lcPathBase = null;
    public static String threadNum1;
    public static String threadNum2;
    public static String threadQueue;
//    public static String localFilePath = null;
    public static String timeout = null;
    public static String ffmpegPath = null;
    public static String confDir = null;
    public static String upLoadFastFlag = null;
    public static BlockingQueue<String> threadList = new LinkedBlockingQueue<String>();//用来存放正在解析的json文件，读入后加入，结束后删除
//    static String logFilePath = BanBkE2p.class.getResource("/").getFile() + "log4j.properties";
//    static String locFilePath = BanBkE2p.class.getResource("/").getFile() + "localfile.properties";

    public static String multimediaurl = null;
    public static String multimedianamebase = null;
    public static ClientAPI mediaclient = null;

    static {
        PropertyConfigurator.configure(ClassLoader.getSystemClassLoader().getResource("log4j.properties"));
        logger = Logger.getLogger(BanBkE2p.class);
    }

    public static void main(String[] args) {
        boolean flag = true;
        Properties prop = new Properties();
        try {
            String locFilePath = ClassLoader.getSystemClassLoader().getResource("localfile.properties").getFile();
            InputStream in = new FileInputStream(locFilePath);
            prop.load(in);
            in.close();
            BanBkE2p.localFilePathBase = prop.getProperty("localfilepath").trim();
            BanBkE2p.lcPathBase = prop.getProperty("lcPathBase").trim();
            BanBkE2p.threadNum1 = prop.getProperty("threadNum1").trim();
            BanBkE2p.threadNum2 = prop.getProperty("threadNum2").trim();
            BanBkE2p.threadQueue = prop.getProperty("threadQueue").trim();
//            BanBkE2p.localFilePath = prop.getProperty("localfilepath").trim();
            BanBkE2p.timeout = prop.getProperty("timeout").trim();
            BanBkE2p.ffmpegPath = prop.getProperty("ffmpegPath").trim();
            BanBkE2p.upLoadFastFlag = prop.getProperty("upload_fast").trim();
            logger.info("localFilePathBase: " + localFilePathBase + " ---------- " + "timeout: " + timeout);
            BanBkE2p.multimediaurl = prop.getProperty("multimediaurl").trim();
            BanBkE2p.multimedianamebase = prop.getProperty("multimedianamebase").trim();
            logger.info("the multimedia url is " + multimediaurl + " ,and the multimedia namebase is " + multimedianamebase);

            //初始化多媒体client
            mediaclient = new ClientAPI();
            try {
                mediaclient.init(BanBkE2p.multimediaurl, BanBkE2p.multimedianamebase);
            } catch (Exception e) {
                logger.error("init multimedia failed, the uri is " + BanBkE2p.multimediaurl + " ,and the namebase is " + BanBkE2p.multimedianamebase);
            }
        } catch (Exception e) {
            flag = false;
            logger.error("localfile.properties file read fail! " + e.getMessage(), e);
        }

        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(Integer.parseInt(threadNum1), Integer.parseInt(threadNum2), 3,
                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(Integer.parseInt(threadQueue)),
                new ThreadPoolExecutor.DiscardOldestPolicy());

        try {//死循环实现轮循目录。
            //起线程池        
            while (true) {
                traverseFolder(localFilePathBase, threadPool);
//                execute(BanBkE2p.localFilePath);//execute函数执行monitor的逻辑
                try {
                    logger.info("2分钟后，继续轮询目录 !!!");
//                    System.out.println("5" + " 分钟后，继续轮询目录。");
                    Thread.sleep(2 * 60000);
                } catch (InterruptedException ex) {
                    logger.error("SLEEP ERROR." + ex.getMessage(), ex);
                }
            }
        } catch (Exception ex) {
            logger.error("EXECUTE ERROR." + ex.getMessage(), ex);
        } finally {
            threadPool.shutdown();
            logger.info("成功停止。");
            logger.info("退出程序。");
        }
    }

    private static void execute(String localFilePath, ThreadPoolExecutor threadPool) {
        logger.info("获取任务目录：" + localFilePath + "/Ctrl");
        String nameSpace = localFilePath.substring(localFilePath.lastIndexOf("/") + 1, localFilePath.length());
        String[] temNameSpace = nameSpace.split("_");
        String sourceFileType;
        if (temNameSpace.length == 2) {
            sourceFileType = nameSpace.split("_")[1];
        } else {
            logger.error("nameSpace Directory structure error!!!");
            return;
        }
        String ctrlPath = localFilePath + "/Ctrl";
        File fileRoot = new File(ctrlPath);
        //return 回到死循环。return之前设置为null，提示JVM可以进行垃圾回收了
        if (!fileRoot.isDirectory()) {//ctrlPath 错误的情况
            logger.fatal("**********************************************************");
            logger.fatal("获取任务目录：" + ctrlPath + " 不存在。");
            logger.fatal("**********************************************************");
            fileRoot = null;
            return;
        }
        String[] allFileList = fileRoot.list();//所有json文件名
        //没有sql文件返回
        if (allFileList.length < 1) {
            logger.info("获取任务目录下没有文件");
            return;
        }
        //判断是否为文件夹
        if (allFileList.length == 1) {
            File fileFlag = new File(ctrlPath + File.separator + allFileList[0]);
            if (fileFlag.isDirectory()) {//是文件夹跳过
                return;
            }
        }

        List<String> jsonNameList = new ArrayList<String>();
        List<String> okList = new ArrayList<String>();
        List<String> dwdList = new ArrayList<String>();
        List<String> otherdwdList = new ArrayList<String>();
        List<String> otherList = new ArrayList<String>();
        for (String f : allFileList) {
            if (PatternTools.matchStr("json", f)) {
                if (f.contains("." + sourceFileType + ".dwd")) {
                    dwdList.add(f);
                } else if (f.endsWith(".ok")) {
                    okList.add(f);
                } else if (f.endsWith(".dwd")) {
                    otherdwdList.add(f);
                } else if (f.endsWith(".json")) {
                    jsonNameList.add(f);
                } else {
                    otherList.add(f);
                }
            }
        }

//        //起线程池
//        ThreadPoolExecutor threadPool = new ThreadPoolExecutor(1, 1, 3,
//                TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(jsonNameList.size()),
//                new ThreadPoolExecutor.DiscardOldestPolicy());

        for (int i = 0; i < jsonNameList.size(); i++) {
            if (PatternTools.matchStr("json", jsonNameList.get(i))) {
                String tmpname = jsonNameList.get(i) + ".ok";
                for (int j = 0; j < okList.size(); j++) {
                    if (tmpname.equals(okList.get(j))) {
                        boolean flag = false;
                        for (int k = 0; k < dwdList.size(); k++) {
                            String tmpdwdname = jsonNameList.get(i) + "." + sourceFileType + ".dwd";
                            if (tmpdwdname.equals(dwdList.get(k))) {
                                flag = true;
                                break;
                            }
                        }
                        if (!flag) {
                            //判断是否已经开始运行
                            boolean alreadyExecute = false;
                            Iterator<String> itr = BanBkE2p.threadList.iterator();
                            while (itr.hasNext()) {
                                if (itr.next().equals(jsonNameList.get(i))) {
                                    alreadyExecute = true;
                                    break;
                                }
                            }
                            if (alreadyExecute) {
                                logger.info(jsonNameList.get(i) + "正在运行，跳过。");
                                continue;
                            }
//                            else {
                            //没有运行添加到队列中
//                                BanBkE2p.threadList.add(jsonNameList.get(i));
//                                new FJRThreadTask(jsonNameList.get(i), BanBkE2p.timeout, localFilePath).run();
//                            }
                            threadPool.execute(new FJRThreadTask(jsonNameList.get(i), BanBkE2p.timeout, localFilePath));
                        }
                    }
                }
            }
        }

//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException ex) {
//        }
//        while (true) {//直至所有线程结束，才继续
//            int activeThread = threadPool.getActiveCount();
//            if (activeThread == 0) {
//                break;
//            } else {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException ex) {
//                    logger.error(ex.getMessage(), ex);
//                }
//            }
//        }
//        threadPool.shutdown();
        fileRoot = null;
        allFileList = null;
        echoRunning();
    }

    private static void echoRunning() {
        if (BanBkE2p.threadList.size() == 0) {
            logger.info("=============[" + BanBkE2p.threadList.size() + "]个过程正在运行。");
        } else {
            logger.info(">>>>>>>>>>>>>[" + BanBkE2p.threadList.size() + "]个过程正在运行。");
            Iterator<String> itr = BanBkE2p.threadList.iterator();
            StringBuffer sb = new StringBuffer();
            sb.append("[");
            while (itr.hasNext()) {
                sb.append(itr.next());
                sb.append(",");
            }
            sb.deleteCharAt(sb.length() - 1);
            sb.append("]");
            logger.debug(">>>>>>>>>>>>>" + sb.toString());
            sb = null;
        }
    }
public static void traverseFolder_new(String path, ThreadPoolExecutor threadPool) {
        String[] paths = path.split("\\|");
    for (String localPath : paths) {
        File file = new File(localPath);
        if (file.exists()&&file.isDirectory()) {
            logger.info("文件夹:" + file.getAbsolutePath());
            execute(localPath, threadPool);
        }else{
            logger.info("文件夹是空的!");
                return;
        }
    }
    }
    public static void traverseFolder(String path, ThreadPoolExecutor threadPool) {

        File file = new File(path);//path=/ybkdata/YBK_DATA
        if (file.exists()) {
            File[] files = file.listFiles();
            if (files.length == 0) {
                logger.info("文件夹是空的!");
                return;
            } else {
                for (File file2 : files) {//file2=各个样本文件夹
                    if (file2.isDirectory()) {
                        logger.info("文件夹:" + file2.getAbsolutePath());
                        String localPath = file2.getAbsolutePath();
                        String[] allFileList = file2.list();
                        String dirs = ";";
                        for (int i = 0; i < allFileList.length; i++) {
                            String dir = allFileList[i];
                            dirs = dirs + dir + ";";
                        }
                        if (dirs.contains(";Ctrl;")) {
                            execute(localPath, threadPool);
                        } else {
                            traverseFolder(file2.getAbsolutePath(), threadPool);
                        }

                    } else {
                        logger.fatal(file2.getAbsolutePath() + " 不是任务目录 。");
                        continue;
                    }
                }
            }
        } else {
            logger.info(path + " 文件夹不存在!");
        }
    }
}
